package com.zhongwang.business.module.contractManage.service;


import com.zhongwang.business.gen.entity.User;
import com.zhongwang.business.module.contractManage.dao.ConContractMainDao;
import com.zhongwang.business.module.contractManage.dao.ContractDao;
import com.zhongwang.business.module.contractManage.model.ConContractFundModel;
import com.zhongwang.business.module.contractManage.model.ConContractMainModel;
import com.zhongwang.business.module.contractManage.model.ContractModel;
import com.zhongwang.business.module.fileManage.dao.FileDao;
import com.zhongwang.business.module.fileManage.model.FileModel;
import com.zhongwang.business.module.system.log.LogService;
import com.zhongwang.business.module.taskManage.dao.TaskDao;
import com.zhongwang.business.module.taskManage.model.TaskModel;
import com.zhongwang.business.util.FileUtils;
import com.zhongwang.business.util.ShiroUtils;
import com.zhongwang.business.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import static java.lang.Integer.parseInt;

@Service
public class ConContractMainService {
    @Autowired
    private ConContractMainDao conContractMainDao;
    @Value("${user.upload.path}")
    private String uploadPath;
    @Autowired
    private FileDao fileDao;
    @Autowired
    private ContractDao contractDao;
    @Autowired
    private LogService logService;
    @Autowired
    private TaskDao taskDao;

    /**
     * 执行添加
     * @param model
     * @return
     */
   public int addConContractMain(ConContractMainModel model){
       int flg=1;
       /**
        * 先执行，合同的基本信息，返回来的id，在执行款项基本信息的插入
        */
       model.setIsDelete(0);
       //保存未提交
       model.setIsStatue(1);
       /**
        * 存储项目的编号***************************
        */
       ContractModel model1=new ContractModel();
       List<ContractModel> subList=contractDao.selectProjectById(model.getFkId());
       /**
        * 循环项目名称
        */
       String name="";
       if(subList.size()==1) {
           name = name + subList.get(0).getCode() ;
       }else {
           for (int k = 0; k < subList.size(); k++) {
               name = name + subList.get(k).getCode() + ";";
           }
       }
       model.setContName(name);
       /**
        * 存储项目的编号***************************
        */
       User user = ShiroUtils.getUser();
       model.setCreateUser(user.getName());
       conContractMainDao.addConContractMain(model);
       logService.saveLog("创建合同", "对应的报价单id："+model.getFkId());
       int id=model.getId();
       if(id>0){

           /**
            * 对应的任务的开始时间人信息更新----开始---
            */
           ConContractMainModel taskModel=new ConContractMainModel();

           taskModel.setLoginUid(user.getId());
           taskModel.setName(user.getName());
           taskModel.setId(id);
           conContractMainDao.updTaskBeginAndUser(taskModel);
           logService.saveLog("创建合同", "更新合同任务的状态为执行中，合同id："+id);
           /**
            * 对应的任务的开始时间人信息更新----结束
            */

           String moneyInfo=model.getMoneyInfo();
           String[] sourceStrArray = moneyInfo.split("\\#");
           for (int i2 = 0; i2 < sourceStrArray.length; i2++) {
               String[] sourceModel = sourceStrArray[i2].split("\\|");
               if (sourceModel.length >=4) {
                   ConContractFundModel fundModel=new ConContractFundModel();
                   fundModel.setFkContId(id);
                   fundModel.setFundId(parseInt(sourceModel[0]));
                   fundModel.setIsNeed(parseInt(sourceModel[1]));
                   fundModel.setOrderNo(i2+1);
                   fundModel.setFundIsAll(0);
                   /**
                    * 付款比例
                    */
                   if(sourceModel[2]!="") {
                       BigDecimal bd = new BigDecimal(sourceModel[2]);
                       fundModel.setFundScale(bd);
                   }
                    /**
                     * 付款金额
                     */
                   if(sourceModel[3]!="") {
                       BigDecimal bd = new BigDecimal(sourceModel[3]);
                       fundModel.setFundMoney(bd);
                   }
                   /**
                    * 回款时间
                    */
                   if(sourceModel.length ==5) {
                       fundModel.setFundDate(sourceModel[4]);
                   }else{
                       fundModel.setFundDate("");
                   }
                /**
                 * 执行款项的添加
                 */
                   if(fundModel.getIsNeed()==1) {
                    conContractMainDao.addConContractFund(fundModel);
                    logService.saveLog("创建合同", "保存合同的款项，款项枚举值："+fundModel.getFundId()+",付款比例："+fundModel.getFundScale().toString()+"%，付款金额："+fundModel.getFundMoney().toString());
                   }
               }
           }

           /**
            * 插入新的款项
            */
           moneyInfo=model.getMoneyInfoAll();
           sourceStrArray = moneyInfo.split("\\#");
           for (int i2 = 0; i2 < sourceStrArray.length; i2++) {
               String[] sourceModel = sourceStrArray[i2].split("\\|");
               if (sourceModel.length >=4) {
                   ConContractFundModel fundModel=new ConContractFundModel();
                   /**
                    * 总包方的信息
                    */
                   fundModel.setFundIsAll(1);
                   fundModel.setFkContId(id);
                   fundModel.setFundId(parseInt(sourceModel[0]));
                   fundModel.setIsNeed(parseInt(sourceModel[1]));
                   fundModel.setOrderNo(i2+1);
                   /**
                    * 付款比例
                    */
                   if(sourceModel[2]!="") {
                       BigDecimal bd = new BigDecimal(sourceModel[2]);
                       fundModel.setFundScale(bd);
                   }
                   /**
                    * 付款金额
                    */
                   if(sourceModel[3]!="") {
                       BigDecimal bd = new BigDecimal(sourceModel[3]);
                       fundModel.setFundMoney(bd);
                   }
                   /**
                    * 回款时间
                    */
                   if(sourceModel.length ==5) {
                       fundModel.setFundDate(sourceModel[4]);
                   }else{
                       fundModel.setFundDate("");
                   }
                   /**
                    * 执行款项的添加
                    */
                   if(fundModel.getIsNeed()==1) {
                    conContractMainDao.addConContractFund(fundModel);
                    logService.saveLog("创建合同", "保存总包方合同的款项，款项枚举值："+fundModel.getFundId()+",付款比例："+fundModel.getFundScale().toString()+"%，付款金额："+fundModel.getFundMoney().toString());
                   }
               }
           }
       }
       return flg;
   }

    /**
     * 执行修改
     * @param model
     * @return
     */
    public int updConContractMain(ConContractMainModel model){
        int flg=1;
        /**
         * 先执行，合同的基本信息，返回来的id，在执行款项基本信息的插入
         */
        model.setIsDelete(0);
        //保存未提交
        model.setIsStatue(1);
        User user = ShiroUtils.getUser();
        model.setCreateUser(user.getName());
        conContractMainDao.updConContractMain(model);
        logService.saveLog("创建合同", "修改合同状态为：保存未提交，合同id："+model.getId());
        int id=model.getId();

        if(id>0){
            /**
             * 先把所有的款项都删除。
             */
            flg=conContractMainDao.delConContractFundById(id);
            /**
             * 插入新的款项
             */
            String moneyInfo=model.getMoneyInfo();
            String[] sourceStrArray = moneyInfo.split("\\#");
            for (int i2 = 0; i2 < sourceStrArray.length; i2++) {
                String[] sourceModel = sourceStrArray[i2].split("\\|");
                if (sourceModel.length >=4) {
                    ConContractFundModel fundModel=new ConContractFundModel();
                    /**
                     * 我方的款项信息
                     */
                    fundModel.setFundIsAll(0);
                    fundModel.setFkContId(id);
                    fundModel.setFundId(parseInt(sourceModel[0]));
                    fundModel.setIsNeed(parseInt(sourceModel[1]));
                    fundModel.setOrderNo(i2+1);
                    /**
                     * 付款比例
                     */
                    if(sourceModel[2]!="") {
                        BigDecimal bd = new BigDecimal(sourceModel[2]);
                        fundModel.setFundScale(bd);
                    }
                    /**
                     * 付款金额
                     */
                    if(sourceModel[3]!="") {
                        BigDecimal bd = new BigDecimal(sourceModel[3]);
                        fundModel.setFundMoney(bd);
                    }
                    /**
                     * 回款时间
                     */
                    if(sourceModel.length ==5) {
                        fundModel.setFundDate(sourceModel[4]);
                    }else{
                        fundModel.setFundDate("");
                    }
                    /**
                     * 执行款项的添加
                     */
                    if(fundModel.getIsNeed()==1) {
                        conContractMainDao.addConContractFund(fundModel);
                        logService.saveLog("修改合同", "保存合同的款项，款项枚举值："+fundModel.getFundId()+",付款比例："+fundModel.getFundScale().toString()+"%，付款金额："+fundModel.getFundMoney().toString());
                    }
                }
            }
            /**
             * 插入新的款项
             */
             moneyInfo=model.getMoneyInfoAll();
             sourceStrArray = moneyInfo.split("\\#");
            for (int i2 = 0; i2 < sourceStrArray.length; i2++) {
                String[] sourceModel = sourceStrArray[i2].split("\\|");
                if (sourceModel.length >=4) {
                    ConContractFundModel fundModel=new ConContractFundModel();
                    /**
                     * 总包方的信息
                     */
                    fundModel.setFundIsAll(1);
                    fundModel.setFkContId(id);
                    fundModel.setFundId(parseInt(sourceModel[0]));
                    fundModel.setIsNeed(parseInt(sourceModel[1]));
                    fundModel.setOrderNo(i2+1);
                    /**
                     * 付款比例
                     */
                    if(sourceModel[2]!="") {
                        BigDecimal bd = new BigDecimal(sourceModel[2]);
                        fundModel.setFundScale(bd);
                    }
                    /**
                     * 付款金额
                     */
                    if(sourceModel[3]!="") {
                        BigDecimal bd = new BigDecimal(sourceModel[3]);
                        fundModel.setFundMoney(bd);
                    }
                    /**
                     * 回款时间
                     */
                    if(sourceModel.length ==5) {
                        fundModel.setFundDate(sourceModel[4]);
                    }else{
                        fundModel.setFundDate("");
                    }
                    /**
                     * 执行款项的添加
                     */
                    if(fundModel.getIsNeed()==1) {
                        conContractMainDao.addConContractFund(fundModel);
                        logService.saveLog("修改合同", "保存总包方合同的款项，款项枚举值："+fundModel.getFundId()+",付款比例："+fundModel.getFundScale().toString()+"%，付款金额："+fundModel.getFundMoney().toString());
                    }
                }
            }
        }
        return flg;
    }

    /**
     * 获得草稿状态下的合同id，便于存储附件啊！
     * @param model
     * @return
     */
   public int getDraftConId(ConContractMainModel model){
       return conContractMainDao.getDraftConId(model);
   }

    /**
     * 上传文件
     * @param file
     * @param mainId 合同id
     * @return
     */
    public int uploadFile(MultipartFile[] file, Integer queId,Integer mainId,String remark,Integer fileType) {
        User user = ShiroUtils.getUser();
        if((mainId==null || mainId==0) && queId!=null && queId>0){
            ConContractMainModel model=new ConContractMainModel();
            model.setFkId(queId);
            model.setCreateUser(user.getName());
            conContractMainDao.getDraftConId(model);
            mainId=model.getId();
            logService.saveLog("上传附件", "保存合同为草稿状态，合同id："+mainId.toString());
        }

        if (null != file && file.length > 0) {
            for (MultipartFile f : file) {
                String path = uploadPath + "contract/" + mainId+ "/";
                String fileName = FileUtils.upload(f, path);
                if (StringUtils.isNotNull(fileName)) {
                    String url = "/files/contract/" + mainId+ "/" + fileName;
                    FileModel fileModel=new FileModel();
                    fileModel.setMainId(mainId);
                    fileModel.setFileName(fileName);
                    fileModel.setFileComment(remark);
                    fileModel.setFileType(fileType);
                    fileModel.setFileUrl(url);
                    fileModel.setUserId(user.getAccount());
                    fileModel.setUserName(user.getName());
                    fileModel.setFileStatus(1);
                    fileDao.addFileInfo(fileModel);
                    logService.saveLog("上传合同附件", "文件类型："+fileType+",文件名称："+fileName+"，备注描述："+remark);
                }
            }
        }
        return mainId;
    }


    /**
     * 上传文件 概算预算核算
     * @param file
     * @param mainId 合同id
     * @return
     */
    public int uploadFileGYH(MultipartFile[] file,Integer mainId,String remark,Integer fileType) {
        User user = ShiroUtils.getUser();

        if (null != file && file.length > 0) {
            for (MultipartFile f : file) {
                String path = uploadPath + "cost/" + mainId+ "/";
                String fileName = FileUtils.upload(f, path);
                if (StringUtils.isNotNull(fileName)) {
                    String url = "/files/cost/" + mainId+ "/" + fileName;
                    FileModel fileModel=new FileModel();
                    fileModel.setMainId(mainId);
                    fileModel.setFileName(fileName);
                    fileModel.setFileComment(remark);
                    fileModel.setFileType(fileType);
                    fileModel.setFileUrl(url);
                    fileModel.setUserId(user.getAccount());
                    fileModel.setUserName(user.getName());
                    fileModel.setFileStatus(1);
                    fileDao.addFileInfo(fileModel);
                    TaskModel taskModel=new TaskModel();
                    /**
                     * 任务变为已完成
                     */
//                    概算	7
//                    预算	1
//                    核算	6
                    if(fileType==29) {
                        taskModel.setTkind(7);
                    }else if(fileType==30){
                        taskModel.setTkind(1);
                    }else if(fileType==35){
                        taskModel.setTkind(6);
                    }
                    taskModel.setTstatus(3);
                    taskModel.setFkId(mainId);
                    taskModel.setKeyPerson(user.getName());
                    taskModel.setKeyPersonId(user.getId());
                    taskDao.updateTaskGYH( taskModel);


                    logService.saveLog("上传概算预算核算附件", "文件类型："+fileType+",文件名称："+fileName+"，备注描述："+remark);
                }
            }
        }
        return mainId;
    }


    /**
     * 上传文件
     * @param file
     * @param fileId 合同id
     * @return
     */
    public int editFileInfo(MultipartFile[] file, Integer mainId,Integer fileId,String fileComment,Integer fileType) {
        int flg=0;
        User user = ShiroUtils.getUser();

        if (null != file && file.length > 0) {
            for (MultipartFile f : file) {
                String path = uploadPath + "contract/" + mainId+ "/";
                String fileName = FileUtils.upload(f, path);
                if (StringUtils.isNotNull(fileName)) {
                    String url = "/files/contract/" + mainId+ "/" + fileName;
                    FileModel fileModel=new FileModel();

                    fileModel.setFileName(fileName);
                    fileModel.setFileComment(fileComment);
                    fileModel.setFileType(fileType);
                    fileModel.setFileUrl(url);
                    fileModel.setFileId(fileId);

                    flg=fileDao.editFileInfo(fileModel);
                    logService.saveLog("编辑合同附件", "文件类型："+fileType+",文件名称："+fileName+"，备注描述："+fileComment);

                }else{
                    FileModel fileModel=new FileModel();
                    fileModel.setFileComment(fileComment);
                    fileModel.setFileType(fileType);
                    fileModel.setFileId(fileId);

                    flg=fileDao.editFileInfo(fileModel);
                    logService.saveLog("编辑合同附件", "文件类型："+fileType+"，备注描述："+fileComment);
                }
            }
        }
        return flg;
    }

    /**
     * 查询合同基本信息
     * @param id
     * @return
     */
    public ConContractMainModel selConContractMain(Integer id){
        return conContractMainDao.selConContractMain(id);
    }

    /**
     * 根据合同id，查询历史的审批记录
     * @param id
     * @return
     */
    public List<ConContractMainModel> selAppList(Integer id){
        return conContractMainDao.selAppList(id);
    }

    /**
     * 查询款项的信息，机械方的
     * @param id
     * @return
     */
    public List<ConContractFundModel> selConFun(Integer id){
        return conContractMainDao.selConFun(id);
    }

    /**
     * 查询款项的信息，总包方的
     * @param id
     * @return
     */
    public List<ConContractFundModel> selConFunOfAll(Integer id){
        return conContractMainDao.selConFunOfAll(id);
    }

    /**
     * 查询款项的信息，机械方的
     * @param id
     * @return
     */
    public List<ConContractFundModel> selConFunEnd(Integer id){
        return conContractMainDao.selConFunEnd(id);
    }

    /**
     * 查询款项的信息，总包方的
     * @param id
     * @return
     */
    public List<ConContractFundModel> selConFunOfAllEnd(Integer id){
        return conContractMainDao.selConFunOfAllEnd(id);
    }

    /**
     * 删除合同
     * @param conId
     * @return
     */

    public int deleteApp(Integer conId) {
        int flg=1;
        try {
            ConContractMainModel main=new ConContractMainModel();
            main.setId(conId);
            conContractMainDao.updConContractMaindDelStatus(main);
        }catch (Exception ex){
            flg=-1;
        }
        return flg;
    }
    /**
     * 提交审核
     * @param conId
     * @return
     */
    public int contractAppInfo(Integer conId){
        int flg=1;
        try {
            //首先修改合同的状态
            ConContractMainModel model=new ConContractMainModel();
            model.setId(conId);
            /**
             * 0未保存1保存未提交2提交待审3审核通过4审核不通过
             */
            model.setIsStatue(2);
            conContractMainDao.updConContractMainStatus(model);
            //单据表增加审核和合同的关系
            ConContractMainModel model_sheet=new ConContractMainModel();
            model_sheet.setBllId(conId);
            User user = ShiroUtils.getUser();
            model_sheet.setSubmitUser(user.getId());
            /**
             * 1预算审核2报价审核3合同审核4款票审核6核算审核7概算审核
             */
            model_sheet.setAppType(3);
            /**
             * 先执行查询
             */
            //如果存在，就直接用id
            ConContractMainModel sheetid= conContractMainDao.selectSheetDetail(conId);
           if(sheetid==null){
               //不存在再直接插入
               conContractMainDao.addSheetDetail(model_sheet);
           }else {
               model_sheet.setId(sheetid.getId());
           }

            //生成下一步待审核的记录************************
            //01 首先需要查询对应的流程信息
            ConContractMainModel addAppInfo=new ConContractMainModel();
            /**
             * 执行成功以后，获取数据的主键
             */
            addAppInfo.setSheetId(model_sheet.getId());
            addAppInfo.setCode("HT001");
            /**
             * 0=被驳回，1=未审核，2=已审核
             */
            addAppInfo.setAppStatus(1);

            //循环判断 当前的账号所在的流程节点；
            List<ConContractMainModel> nowUserNodeInfo=conContractMainDao.selAppNodeInfoByUserId(user.getId());
            //分2种情况
            if(nowUserNodeInfo==null || nowUserNodeInfo.size()==0) {
                //无数据；1·没有再审批节点中，是员工级别的，那么直接就按照流程顺序走。
                List<ConContractMainModel> appList=conContractMainDao.selAppNodeInfo(0);
                // 然后在找下一个节点和下下节点。

                /**
                 * 上一个节点是0
                 */
                addAppInfo.setComp(0);

                /**
                 * 判断流程节点，是1个还是2个及以上。
                 */
                if(appList!=null && appList.size()==1){
                    //获取第一条数据，为当前的节点号，执行人。
                    //获取第二条数据的，节点。
                    addAppInfo.setNowNode(appList.get(0).getId());
                    addAppInfo.setOrderNo(appList.get(0).getOrderNo());
                    addAppInfo.setStart(0);
                    /**
                     * 根据我当前登录的账号，和流程配置的级别，找到那个人、
                     */
                    int pid=conContractMainDao.selNowLevelByUserId(user.getId());
                    /**
                     * 执行递归查询
                     */
                    addAppInfo.setVerifier(getPid(appList.get(0).getPost(),pid));

                }else if(appList!=null && appList.size()>=2){
                    addAppInfo.setNowNode(appList.get(0).getId());
                    addAppInfo.setOrderNo(appList.get(0).getOrderNo());
                    /**
                     * 根据我当前登录的账号，和流程配置的级别，找到那个人、
                     */
                    int pid=conContractMainDao.selNowLevelByUserId(user.getId());
                    /**
                     * 执行递归查询
                     */
                    addAppInfo.setVerifier(getPid(appList.get(0).getPost(),pid));
                    addAppInfo.setStart(appList.get(1).getId());
                }

                // 然后判断下一个节点和下下节点是不是最后一个节点
            }else {
             //有数据；2·在流程的中间，那么返回它的，顺序、是否为起点、是否为终点。
                List<ConContractMainModel> appList2=conContractMainDao.selAppNodeInfo(nowUserNodeInfo.get(0).getOrderNo());

                /**
                 * 上一步，一定是0 ，因为我是申请啊。
                 */
                addAppInfo.setComp(0);
                /**
                 * 下一步，是流程的下一步
                 */
                addAppInfo.setStart(nowUserNodeInfo.get(0).getId());
                addAppInfo.setNowNode(appList2.get(0).getId());
                addAppInfo.setOrderNo(appList2.get(0).getOrderNo());

                int pid = conContractMainDao.selNowLevelByUserId(user.getId());
                /**
                 * 执行递归查询
                 */
                addAppInfo.setVerifier(getPid(appList2.get(0).getPost(), pid));
            }
            conContractMainDao.addVerifyProcess(addAppInfo);

        }catch (Exception ex){
            flg=-1;
        }
        return flg;
    }

    /**
     * 递归：直到找到审批级别的上级人员id为止
     * @param post
     * @param pid
     * @return
     */
    private int getPid(int post,int pid){
        int userId=0;
        ConContractMainModel nextModel=conContractMainDao.selNextLevelUserByPId(pid);
        if(nextModel!=null){
            if(nextModel.getPost()==post) {
                userId=nextModel.getSubmitUser();
            }else{
                getPid(post,nextModel.getParentId());
            }
        }
        return userId;
    }

    /**
     * 待审批列表
     * @param model
     * @return
     */
    public List<ConContractMainModel> unAppContractList(ConContractMainModel model){
        User user = ShiroUtils.getUser();
        model.setLoginUid(user.getId());
        List<ConContractMainModel> list=conContractMainDao.unAppContractList(model);


        int m = list.size();
        for (int i = 0; i < m; i++) {
            ContractModel model1=new ContractModel();
            List<ContractModel> subList=contractDao.selectProjectById(list.get(i).getFkId());
            /**
             * 循环项目名称
             */
            String name="";
            String contName="";
            for (int k= 0; k < subList.size(); k++) {
                name=name+subList.get(k).getName()+"</br>";
                contName=contName+subList.get(k).getCode()+"</br>";
            }
            list.get(i).setProjectName(name);
            list.get(i).setLoginUid( user.getId());
            list.get(i).setContName(contName);
        }
        return list;
    }

    /**
     * 待创建增补协议列表
     * @param model
     * @return
     */
    public List<ConContractMainModel> appendContractList(ConContractMainModel model){

        List<ConContractMainModel> list=conContractMainDao.appendContractList(model);


        int m = list.size();
        for (int i = 0; i < m; i++) {
            ContractModel model1=new ContractModel();
            List<ContractModel> subList=contractDao.selectProjectById(list.get(i).getFkId());
            /**
             * 循环项目名称
             */
            String name="";
            String contName="";
            for (int k= 0; k < subList.size(); k++) {
                name=name+subList.get(k).getName()+"</br>";
                contName=contName+subList.get(k).getCode()+"</br>";
            }
            list.get(i).setProjectName(name);
            list.get(i).setContName(contName);
        }
        return list;
    }
    /**
     * 流程审批
     * @param model
     * @return
     */

    public int contractAppInfoByUserRole(ConContractMainModel model){
        int flg=1;
        //上一步骤的审批结果，是看还是不看。
        return flg;
    }

    /**
     * 根据id 处理审批
     * @param model
     * @return
     */
    public int approveInfoByBllId(ConContractMainModel model){
        int flg=1;
        //当前的数据id
        //appStatus 审批状态 0 ng 2 ok
        //remark 审批意见
        try {
            conContractMainDao.updVerifyProcess(model);
            //根据当前的节点，OK NG+意见
            //1·OK
            ConContractMainModel nowProcess = conContractMainDao.selectVerifyProcess(model.getId());
            //循环判断 当前的账号所在的流程节点；
            User user = ShiroUtils.getUser();
            List<ConContractMainModel> nowUserNodeInfo=conContractMainDao.selAppNodeInfoByUserId(user.getId());
            /**
             * 审批状态为2时；代表通过
             */
            if (model.getAppStatus() == 2) {
                /**
                 * 下一个节点=0 就是当前是最后的节点了，需要修改业务主表的状态值
                 */
                if (nowProcess.getStart() == 0) {
                    //1.1·当前是否是最后一个节点
                    //1.1.1·修改业务主表的状态值

                    /**
                     * con_contract_main is_statue:3审核通过4审核不通过
                     */
                    model.setIsStatue(3);
                    conContractMainDao.updContractStatuse(model);
                    logService.saveLog("合同审核", "通过");

                    /**
                     * 同时修改任务对应的合同的进度；
                     */
                    conContractMainDao.updTaskstatuse(model.getId());
                    logService.saveLog("合同审核", "通过，修改对应的合同任务为已完结");
                    /**
                     * 更新款票的开始时间
                     */
                    conContractMainDao.updTaskKPStatuse(model.getId());
                    logService.saveLog("合同审核", "通过，修改对应的款票任务为执行中");
                    /***
                     * 判断是否是增补合同，如果是，需要进行调整。
                     */
                    ConContractMainModel isParentModel=conContractMainDao.selIsAppendContract(model.getId());
                    //0 是正常的合同
                    if(isParentModel.getParentId()==0){
                        /**
                         * 同时生成合同对应的款项
                         */
                        conContractMainDao.makeMoneyFund(model.getId());
                        logService.saveLog("合同审核", "通过，生成对应的款票信息");
                    }else{
                        //否则就是增补合同
                        //先删除原来的合同的款项
                        conContractMainDao.deleteReturnMoneyInfo(isParentModel.getParentId());
                        logService.saveLog("增补合同审核", "通过，删除对应的款票信息，合同id："+isParentModel.getId().toString());
                        //再根据最后的增补合同，生成款项。
                        conContractMainDao.addNewReturnMoneyInfo(isParentModel.getId());
                        logService.saveLog("增补合同审核", "通过，重新生成对应的款票信息，合同id："+isParentModel.getId().toString());
                    }
                } else {
                    //1.2·找到下一个节点、下下个节点、审批人
                    List<ConContractMainModel> appList = conContractMainDao.selAppNodeInfo(nowUserNodeInfo.get(0).getOrderNo());
                    /**
                     * 根据我当前登录的账号，和流程配置的级别，找到那个人、
                     */
                    ConContractMainModel addAppInfo = new ConContractMainModel();

                    int pid = conContractMainDao.selNowLevelByUserId(user.getId());
                    /**
                     * 执行递归查询
                     */
                    addAppInfo.setVerifier(getPid(appList.get(0).getPost(), pid));
                    addAppInfo.setNowNode(appList.get(0).getId());
                    addAppInfo.setOrderNo(appList.get(0).getOrderNo());

                    if (appList != null && appList.size() >= 2) {
                        addAppInfo.setStart(appList.get(1).getId());
                    } else {
                        addAppInfo.setStart(0);
                    }
                    //下一个节点的，上一个节点是现在的id
                    addAppInfo.setComp(nowProcess.getNowNode());
                    addAppInfo.setCode("HT001");
                    addAppInfo.setSheetId(nowProcess.getSheetId());
                    addAppInfo.setAppStatus(1);
                    conContractMainDao.addVerifyProcess(addAppInfo);
                    logService.saveLog("合同审核", "通过，生成下一个审批人记录，合同单据表id："+nowProcess.getSheetId().toString());

                }
            } else {
                //2·NG+意见
                //2.1·存储当前的状态+结果
                if (nowProcess.getComp() == 0) {
                    //2.2.1·如果上一个是提交的话，修改业务主表的状态值
                    /**
                     * con_contract_main is_statue:3审核通过4审核不通过
                     */
                    model.setIsStatue(4);
                    conContractMainDao.updContractStatuse(model);
                    logService.saveLog("合同审核","驳回，修改合同的状态为驳回");
                } else {
                    //2.2·找到上一个节点，生成下一个节点、审批人//
                    /**
                     * 根据我当前审批记录，找到我上一个临近的、
                     */
                    ConContractMainModel addAppInfo=conContractMainDao.selNextUserByNgInfo(model.getId());
                    addAppInfo.setAppStatus(1);
                    conContractMainDao.addVerifyProcess(addAppInfo);
                    logService.saveLog("合同审核","驳回，生成下一条审批人的记录");
                }
            }
        }catch (Exception ex){
            flg=-1;
        }
        return flg;
    }
    /**
     * 合同待签订列表
     * @param model
     * @return
     */
    public List<ConContractMainModel> selContractList(ConContractMainModel model) {
        List<ConContractMainModel> list=conContractMainDao.selectContractList(model);
        int m = list.size();
        for (int i = 0; i < m; i++) {
            ContractModel model1=new ContractModel();
            List<ContractModel> subList=contractDao.selectProjectById(list.get(i).getFkId());
            /**
             * 循环项目名称
             */
            String name="";
            String consumerName="";
            for (int k= 0; k < subList.size(); k++) {
                name=name+subList.get(k).getCode()+"</br>";
                consumerName=consumerName+subList.get(k).getConsumerName()+"</br>";
            }
            list.get(i).setContName(name);
            list.get(i).setRemark(consumerName);
        }
        return list;
    }

    /**
     * 合同查询页面
     * @param model
     * @return
     */
    public List<ContractModel> selAllContract(ContractModel model) {
        List<ContractModel> list=conContractMainDao.selAllContractSearch(model);
        int m = list.size();
        for (int i = 0; i < m; i++) {
            ContractModel model1=new ContractModel();
            List<ContractModel> subList=contractDao.selectProjectById(list.get(i).getQuoteId());

            /**
             * 循环项目名称
             */
            String name="";
            String contName="";
            if(subList.size()==1) {
                name =  subList.get(0).getName() ;
                contName=subList.get(0).getCode() ;
            }else {
                for (int k = 0; k < subList.size(); k++) {
                    name = name + subList.get(k).getName() + "</br>";
                    contName = contName + subList.get(k).getCode() + "</br>";
                }
            }
            list.get(i).setCode(contName);
            list.get(i).setContName(name);
        }
        return list;
    }
    /**
     * 查看全部的增补协议
     * @return
     */
    public List<ConContractMainModel> selectAppConList(Integer id){
        return conContractMainDao.selectAppConList(id);
    }

    /**
     * 修改合同状态
     * @return
     */
    public int updContWay(Integer id,String contWay){
        ConContractMainModel model=new ConContractMainModel();
        model.setId(id);
        model.setContWay(contWay);
        return conContractMainDao.updContWay(model);
    }

    /**
     * 查询人员的集合
     * @return
     */
    public List<ConContractMainModel> selUser(){
        return conContractMainDao.selUser();
    }

    /**
     * 修改人名
     * @param model
     * @return
     */
    public int updateName(ConContractMainModel model) {
        return conContractMainDao.updateName(model);
    }
}
